from django.db import models
from django.contrib.auth.models import User


class Scene(models.Model):
    """智能场景模型"""
    TRIGGER_TYPE_CHOICES = [
        ('manual', '手动触发'),
        ('time', '定时触发'),
        ('device_status', '设备状态触发'),
        ('weather', '天气条件触发'),
        ('location', '位置触发'),
    ]

    name = models.CharField(max_length=100, verbose_name="场景名称")
    description = models.TextField(blank=True, verbose_name="场景描述")
    icon = models.CharField(max_length=50, blank=True, verbose_name="场景图标")
    trigger_type = models.CharField(max_length=20, choices=TRIGGER_TYPE_CHOICES, default='manual', verbose_name="触发类型")
    trigger_conditions = models.JSONField(default=list, verbose_name="触发条件")
    actions = models.JSONField(default=list, verbose_name="执行动作")
    is_active = models.BooleanField(default=True, verbose_name="是否启用")
    owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="所有者")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "智能场景"
        verbose_name_plural = "智能场景"
        ordering = ['-updated_at']

    def __str__(self):
        return self.name

    def can_execute(self):
        """检查场景是否可以执行"""
        return self.is_active and len(self.actions) > 0

    def get_devices_count(self):
        """获取场景涉及的设备数量"""
        device_ids = set()
        for action in self.actions:
            if 'device_id' in action:
                device_ids.add(action['device_id'])
        return len(device_ids)


class SceneExecution(models.Model):
    """场景执行记录"""
    EXECUTION_STATUS_CHOICES = [
        ('pending', '待执行'),
        ('running', '执行中'),
        ('success', '成功'),
        ('partial_success', '部分成功'),
        ('failed', '失败'),
        ('cancelled', '已取消'),
    ]

    scene = models.ForeignKey(Scene, on_delete=models.CASCADE, verbose_name="执行场景")
    user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, verbose_name="执行用户")
    trigger_source = models.CharField(max_length=50, blank=True, verbose_name="触发源")
    execution_time = models.DateTimeField(auto_now_add=True, verbose_name="执行时间")
    status = models.CharField(max_length=20, choices=EXECUTION_STATUS_CHOICES, default='pending', verbose_name="执行状态")
    result = models.JSONField(default=dict, verbose_name="执行结果")
    error_message = models.TextField(blank=True, verbose_name="错误信息")
    duration = models.DurationField(blank=True, null=True, verbose_name="执行时长")
    completed_at = models.DateTimeField(blank=True, null=True, verbose_name="完成时间")

    class Meta:
        verbose_name = "场景执行记录"
        verbose_name_plural = "场景执行记录"
        ordering = ['-execution_time']

    def __str__(self):
        return f"{self.scene.name} - {self.get_status_display()} ({self.execution_time.strftime('%Y-%m-%d %H:%M')})"

    @property
    def is_completed(self):
        """检查执行是否已完成"""
        return self.status in ['success', 'partial_success', 'failed', 'cancelled']

    def get_success_rate(self):
        """获取执行成功率"""
        if not self.result or 'actions' not in self.result:
            return 0
        
        total_actions = len(self.result['actions'])
        if total_actions == 0:
            return 0
            
        successful_actions = sum(1 for action in self.result['actions'] if action.get('status') == 'success')
        return (successful_actions / total_actions) * 100


class SceneSchedule(models.Model):
    """场景定时任务模型"""
    SCHEDULE_TYPE_CHOICES = [
        ('once', '单次执行'),
        ('daily', '每日执行'),
        ('weekly', '每周执行'),
        ('monthly', '每月执行'),
        ('cron', 'Cron表达式'),
    ]

    scene = models.ForeignKey(Scene, on_delete=models.CASCADE, verbose_name="关联场景")
    name = models.CharField(max_length=100, verbose_name="任务名称")
    schedule_type = models.CharField(max_length=20, choices=SCHEDULE_TYPE_CHOICES, verbose_name="调度类型")
    schedule_time = models.TimeField(verbose_name="执行时间")
    schedule_date = models.DateField(blank=True, null=True, verbose_name="执行日期")
    cron_expression = models.CharField(max_length=100, blank=True, verbose_name="Cron表达式")
    is_active = models.BooleanField(default=True, verbose_name="是否启用")
    last_run = models.DateTimeField(blank=True, null=True, verbose_name="最后执行时间")
    next_run = models.DateTimeField(blank=True, null=True, verbose_name="下次执行时间")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "场景定时任务"
        verbose_name_plural = "场景定时任务"
        ordering = ['next_run']

    def __str__(self):
        return f"{self.scene.name} - {self.name}"

    def should_run_now(self):
        """检查是否应该立即执行"""
        if not self.is_active or not self.next_run:
            return False
        
        from django.utils import timezone
        return timezone.now() >= self.next_run

    def calculate_next_run(self):
        """计算下次执行时间"""
        from django.utils import timezone
        from datetime import datetime, timedelta
        
        now = timezone.now()
        
        if self.schedule_type == 'once':
            if self.schedule_date and self.schedule_time:
                next_run = timezone.make_aware(
                    datetime.combine(self.schedule_date, self.schedule_time)
                )
                if next_run > now:
                    return next_run
        elif self.schedule_type == 'daily':
            next_run = now.replace(
                hour=self.schedule_time.hour,
                minute=self.schedule_time.minute,
                second=0,
                microsecond=0
            )
            if next_run <= now:
                next_run += timedelta(days=1)
            return next_run
        elif self.schedule_type == 'weekly':
            # 这里可以添加更复杂的周期性计算逻辑
            pass
        
        return None
